import {
  getMRPModuleByPage,
  addMRPModule,
  updateMRPModule,
  delMRPModule,
  getMRPModuleList,
} from '@/services/drivepara/MRPmodule';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Form, message, Modal, Select, Tag } from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';

import React, { useMemo, useRef, useState } from 'react';
import { useAccess, useLocation } from 'umi';

const MRPmodule: React.FC<{}> = () => {
  const [formTitle, setFormTitle] = useState('New log');
  const actionRef = useRef<ActionType>();
  const [formVisit, setFormVisit] = useState(false);
  const [formDisabled, setFormDisabled] = useState(false); //设置表单禁用
  const access = useAccess();
  const formRef = useRef(null);
  const [rowData, setRowData] = useState({ id: '' }); // 保存行值
  const [deleteVisit, setDeleteVisit] = useState(false); // 删除提示框
  const [isCreate, setIsCreate] = useState(false);

  const columns: ProColumns[] = [
    {
      title: 'index',
      dataIndex: 'index',
      valueType: 'index',
      width: 60,
    },
    {
      title: 'identification',
      search: false,
      hideInTable: true,
      dataIndex: 'identification',
      width: 150,
    },
    {
      title: 'item code',
      dataIndex: 'itemCode',
      valueType: 'select',
      valueEnum: {
        1: 'test 1',
        2: 'test 2',
        3: 'test 3',
      },
      width: 100,
    },
    {
      title: 'batch',
      // search: false,
      dataIndex: 'batch',
      width: 110,
    },
    {
      title: 'order multiples',
      // search: false,
      dataIndex: 'orderMultiples',
      width: 120,
    },
    {
      title: 'safe stock',
      // search: false,
      dataIndex: 'safeStock',
      width: 120,
    },
    {
      title: 'gross requirement',
      // search: false,
      dataIndex: 'grossRequirement',
      width: 120,
    },
    {
      title: 'net requirement',
      // search: false,
      dataIndex: 'netRequirement',
      width: 120,
    },

    {
      title: 'operation',
      align: 'center',
      sorter: true,
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      render: (text, record, _, action) => {
        const buttonList = [];
        if (access.canAdmin() || access.canChiefEngineer()) {
          buttonList.push(
            <a
              key="editable"
              onClick={() => {
                action?.startEditable?.(record.id);
                setIsCreate(false);
              }}
            >
              edit
            </a>,
          );

          buttonList.push(
            <a
              key="deleteKey"
              onClick={() => {
                Modal.confirm({
                  title: 'Delete MRP log',
                  content: 'R u sure to delete MRP log?',
                  okText: 'Yes',
                  cancelText: 'No',
                  onOk: async () => {
                    await delMRPModule({ id: record.id });
                    actionRef.current?.reload();
                  },
                });
              }}
            >
              delete
            </a>,
          );
        }

        return buttonList;
      },
    },
  ];

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <ProTable
        headerTitle="MRP form"
        actionRef={actionRef}
        rowKey="id"
        editable={{
          type: 'multiple',
          onSave: async (rowKey, row) => {
            console.log(row);
            delete row.index;
            delete row.createDate;
            delete row.createName;
            if (isCreate) {
              delete row.title;
              delete row.id;
              await addMRPModule(row);
              message.success('Add successfully!');
            } else {
              await updateMRPModule(row);
              message.success('Update successfully!');
            }
            actionRef.current.reload();
          },
        }}
        toolBarRender={(action, { selectedRows, selectedRowKeys }) => {
          return [
            <Button
              key="button"
              icon={<PlusOutlined />}
              onClick={() => {
                actionRef.current?.addEditRecord?.({
                  id: (Math.random() * 1000000).toFixed(0),
                  title: 'New log',
                });
                setIsCreate(true);
              }}
              type="primary"
            >
              New
            </Button>,

            <Button
              key="button"
              icon={<PlusOutlined />}
              onClick={() => {
                Modal.confirm({
                  title: 'Delete log',
                  content: 'R u sure to delete log?',
                  okText: 'Yes',
                  cancelText: 'No',
                  onOk: async () => {
                    await delMRPModule(selectedRowKeys);
                    actionRef.current.reload();
                  },
                });
              }}
              type="primary"
            >
              Delete
            </Button>,
          ];
        }}
        request={async (params = {}, sort, filter) => {
          const result = await getMRPModuleByPage(params);
          console.log(result);
          return {
            data: result.data.content,
            total: result.data.totalElements,
            success: result.success,
          };
        }}
        columns={columns}
        rowSelection={{}}
        scroll={{ x: 2000, y: 350 }}
      />
    </PageHeaderWrapper>
  );
};

export default MRPmodule;
